package com.cn.example.demo.config.restful;

import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 返回Rest风格的数据
 * 
 * @author yhr
 */
@ControllerAdvice(basePackages = "com.cn.example.demo.controller")
public class RestResultWrapper implements ResponseBodyAdvice<Object> {
	private final static Logger logger = LogManager.getLogger(RestResultWrapper.class);

	static {
		logger.info("---->完成数据统一化封装。。。");
	}

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        RestResult result = new RestResult(true, "200", body, null);
        if (body instanceof String) {
        	try {
    			return new ObjectMapper().writeValueAsString(result);
    		} catch (JsonProcessingException jpe) {
    			jpe.printStackTrace();
    			return new RestResult(true, "200", "", null);
    		}
        } else {      	
        	if (body == null) {
				return new RestResult(true, "200", new HashMap<>(), null);
			} else {
				return result;
			}
        }
    }
}
